<template>
  <FPage style="flex: 1">
    <template v-slot:header>
      <div style="padding: 5px 0 5px 10px">
        <el-button icon="add" type="primary" round
                   :loading="loading" @click="addNewUnit">新建
        </el-button>
        <el-button icon="edit" round @click="editUnit"
                   :loading="loading" :disabled="!editable">修改
        </el-button>
        <el-button icon="delete" type="warning" round :loading="loading"
                   :disabled="!editable" @click="removeUnit">删除
        </el-button>
      </div>
    </template>
    <div style="height: 100%; padding: 0 5px">
      <el-table height="100%" border stripe :default-sort="sortConfig" @row-click="rowClick"
                :data="dataSource" @sort-change="sortChange" @selection-change="selectionChange"
                v-loading="loading">
        <el-table-column type="selection" width="40"/>
        <el-table-column show-overflow-tooltip sortable prop="unitName" label="单位名称"/>
        <el-table-column show-overflow-tooltip sortable prop="sort" label="排序号"/>
        <el-table-column show-overflow-tooltip sortable prop="simpleName" label="单位简称"/>
        <el-table-column show-overflow-tooltip prop="parentUnitName" label="上级单位"/>
        <el-table-column show-overflow-tooltip sortable prop="unitCode" label="单位编码"/>
        <el-table-column show-overflow-tooltip sortable prop="unitStatus" label="状态">
          <template #default="{row}">
            <SystemDict :disabled="true" v-model="row.unitStatus" dict-code="unitStatus"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template v-slot:footer>
      <div style="display: flex; justify-content: end; width: 100%; padding: 10px; box-sizing: border-box">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="pageOptions"
          background layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total" small
          @size-change="search"
          @current-change="pageChange"
        />
      </div>
    </template>
  </FPage>
</template>
<script setup>
import FPage from '@/components/layout/FPage.vue';
import {computed, defineOptions, onMounted, shallowRef} from 'vue';
import TableSearchUtils from '@/utils/TableSearchUtils';
import {deleteAction, getAction} from '@/request/BaseRequest';
import SystemDict from '@/components/SystemDict';
import {ElMessage, ElMessageBox} from 'element-plus';

const emits = defineEmits(['selectChange', 'addNewUnit', 'reloadUnits']);
defineOptions({
  name: 'UnitManageComponent'
});

onMounted(() => {
  search();
});

const searchForm = {
  value: {
    validate(call) {
      call(true);
    },
  }
};
const searchParams = shallowRef({
  type: 0
});

function doSearch(searchData) {
  loading.value = true;
  getAction('/sys/unit/loadUnitPage', searchData).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setSearchResult(result);
    }
  });
}

function removeUnit() {
  loading.value = true;
  getAction('/sys/unit/canRemove', {id: selectedRows.value[0].id}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      if (result.canRemove) {
        ElMessageBox.confirm('删除后无法恢复, 确定删除吗? ', '确定删除?', {
          draggable: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          doRemoveUnit();
        });
      } else {
        ElMessage({
          message: result.message,
          type: 'warning',
        });
      }
    }
  });
}

function doRemoveUnit() {
  loading.value = true;
  deleteAction('/sys/unit/removeById',
    {id: selectedRows.value[0].id}).then(data => {
    loading.value = false;
    if (data.success) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
      search(true);
      emits('reloadUnits');
    }
  });
}

function addNewUnit() {
  emits('addNewUnit');
}

const editable = computed(() => {
  return selectedRows.value.length === 1;
});

function doEdit(unit) {
  emits('selectChange', unit);
  // if (isGroup(unit)) {
  //   emits('selectChange', unit);
  // } else {
  //   emits('selectChange', unit);
  // }
}

function editUnit() {
  let unit = selectedRows.value[0];
  doEdit(unit);
}

function isGroup(unit) {
  return unit.unitGroup;
}

function onRowClick(unit) {
  doEdit(unit);
}

function onSelection() {
}

const {
  loading, rowClick, search, selectionChange, setSearchResult, pageOptions, pageChange,
  sortChange, dataSource, resetQueryParams, sortConfig, selectedRows, pagination
} = TableSearchUtils({
  refForm: searchForm,
  doSearch,
  defaultSortConfig: {
    prop: 'sort',
    order: 'ascending',
  },
  searchParams,
  rowClick: onRowClick,
  selectionChange: onSelection
});
</script>
